package com.szbber.commen.utils

import android.graphics.Bitmap
import android.widget.ImageView
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.MultiFormatWriter
import java.util.*

class QRcode {

    /**
     * 根据内容，生成指定宽高、指定格式的二维码图片
     * @param text   内容
     * @param imageView  控件
     * @return 生成的二维码图片
     * @throws Exception
     */
    @Throws(Exception::class)
    fun generateQRCode(text: String, imageView: ImageView): Bitmap? {

        val w = imageView.width
        val h = imageView.height

        val hints: Hashtable<EncodeHintType, Any?> = Hashtable()
        hints[EncodeHintType.CHARACTER_SET] = "utf-8"
        hints[EncodeHintType.MARGIN] = "0"
        val bitMatrix = MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, w, h, hints)
        val pixels = IntArray(w * h)

        for (y in 0 until h) {
            for (x in 0 until w) {
                if (bitMatrix[x, y]) {
                    pixels[y * w + x] = -0x1000000
                } else {
                    pixels[y * w + x] = -0x1
                }
            }
        }
        val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
        bitmap.setPixels(pixels, 0, w, 0, 0, w, h)
        return bitmap

    }


}